﻿using Newtonsoft.Json;
using QuickPasteToolWeb.Infrastructure;
using QuickPasteToolWeb.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuickPasteToolWeb.Helper
{
    /// <summary>
    /// 获取默认及用户配置
    /// </summary>
    public static class SettingHelper
    {
        private static readonly string _userSettingPath = QuickPasteConst.UserSettingPath;

        private static bool isCustom;

        public static SettingModel GetDefaultSetting()
        {
            var folder = ConfigurationManager.AppSettings["folder"];
            var showType = ConfigurationManager.AppSettings["ShowType"];
            var isOpenWebSearch = ConfigurationManager.AppSettings["IsOpenWebSearch"];
            var defaultSetting = new SettingModel()
            {
                Folder = folder,
                ShowType = (ShowType)int.Parse(showType),
                IsOpenWebSearch = bool.Parse(isOpenWebSearch),
            };
            return defaultSetting;
        }

        public static SettingModel GetSetting()
        {
            if (isCustom)
            {
                return GetUserSetting(); ;
            }
            else
            {
                return GetDefaultSetting();
            }
        }

        public static void SaveSetting(SettingModel settingModel)
        {
            var setting = JsonConvert.SerializeObject(settingModel);
            isCustom = true;
            File.WriteAllText(_userSettingPath, setting);
        }

        public static void ResetSetting()
        {
            if (File.Exists(_userSettingPath))
            {
                isCustom = false;
                File.Delete(_userSettingPath);
            }
        }

        public static void InitSetting()
        {
            var folder = ConfigurationManager.AppSettings["folder"];
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
        }

        private static SettingModel GetUserSetting()
        {
            return JsonConvert.DeserializeObject<SettingModel>(File.ReadAllText(_userSettingPath));
        }
        public static string GetFolder()
        {
            if (!isCustom)
            {
                return ConfigurationManager.AppSettings["folder"];
            }
            else
            {
                return GetUserSetting().Folder;
            }
        }
    }
}
